package com.kld.simplelauncher.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.health.connect.datatypes.AppInfo;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.content.FileProvider;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class AppUtils {
    private static final String TAG = "AppUtils";
    private static AppUtils instance;

    private AppUtils() {

    }

    public static AppUtils getInstance() {
        if (instance == null) {
            instance = new AppUtils();
        }
        return instance;
    }

    private static List<PackageInfo> appInfoList = null;

    /**
     * 启动的App包名
     *
     * @param packageName
     */
    public static void startApplication(Context context,String packageName) {
        Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 启动App方法
     *
     * @param PackageName 传入要启动的App包名
     */
    public static void startApp(Context context,String PackageName) {
        if(!TextUtils.isEmpty(PackageName)) {
            Log.d("TAG", "打开包名为:" + PackageName);
            try {
                Intent startIntent = context.getPackageManager().getLaunchIntentForPackage(PackageName);
//                startIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(startIntent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 判断系统中是否安装某个应用
     *
     * @param PackageName 传入要判断的包名
     * @return 返回true表示存在，其它则不存在
     */
    public static boolean IsInstallApk(Context context, String PackageName) {
        PackageManager manager = context.getPackageManager();
        List<PackageInfo> AppInfo = manager.getInstalledPackages(0);//获取所有安装的包名
        for (int i = 0; i < AppInfo.size(); i++) {
            //AppInfo.get(i).applicationInfo.loadIcon(manager);
            String Name = AppInfo.get(i).packageName;
            if (Name.equals(PackageName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取系统安装的所有App信息
     *
     * @param mContext 传进行当前使用的上下文
     * @return 返回所有App信息集合
     */
    public static List<PackageInfo> getAppInfos(Context mContext) {
        PackageManager pm = mContext.getPackageManager();
        List<PackageInfo> packagerInfos = pm.getInstalledPackages(0);
        List<PackageInfo> AppInfos = new ArrayList<PackageInfo>();
        for (PackageInfo infos : packagerInfos) {
            String packager_name = infos.packageName;
            Drawable icon_launcher = infos.applicationInfo.loadIcon(pm);
            String App_Name = infos.applicationInfo.loadLabel(pm).toString();
            int flags = infos.applicationInfo.flags;
            AppInfos.add(infos);
        }
        return AppInfos;
    }

    public static List<PackageInfo> getUserAppInfo(Context mContext) {
        PackageManager pm = mContext.getPackageManager();
        List<PackageInfo> packagerInfos = pm.getInstalledPackages(0);
        if (appInfoList == null) {
            appInfoList = new ArrayList<>();
        } else {
            appInfoList.clear();
        }
        for (PackageInfo infos : packagerInfos) {
            String packager_name = infos.packageName;
            Drawable icon_launcher = infos.applicationInfo.loadIcon(pm);
            String App_Name = infos.applicationInfo.loadLabel(pm).toString();
            int flags = infos.applicationInfo.flags;
            if ((ApplicationInfo.FLAG_SYSTEM & flags) != 0) {
                //系统应用
                //info.setSystem_App(true);
            } else {
                appInfoList.add(infos);
            }

        }
        return appInfoList;
    }

    /**
     * 卸载APK
     * @param packageName
     */
    public static void unInstallApk(Context context,String packageName) {
        if (!TextUtils.isEmpty(packageName) && !packageName.equals("com.tfx.activity")) {
            Uri packageURI = Uri.parse("package:" + packageName);
            Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
            uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(uninstallIntent);
        }
    }

    public static void installApk(Context context, File binaryFile) {
        //判断版本大于等于7.0
        //Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Intent intent = new Intent();
            intent.setAction(android.content.Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            String applicationId = context.getPackageName() + ".fileProvider";
            Uri uri = FileProvider.getUriForFile(context, applicationId, binaryFile);
            //给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            context.startActivity(intent);
        } else {
            Intent intent = new Intent();
            intent.setAction(android.content.Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(binaryFile);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            context.startActivity(intent);
        }
    }
    public static boolean doRunActivity(Context context, String packageName, String name) {
        boolean ret = false;
        try {
            Intent it = new Intent(Intent.ACTION_VIEW);
            it.setClassName(packageName, name);
            it.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(it);
            ret = true;
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
        return ret;
    }
    // 获取所有的应用
    public static List<PackageInfo> getAllApp(Context context) {
        PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> packages = packageManager.getInstalledPackages(PackageManager.GET_META_DATA);
        return packages;
    }
    public static List<ApplicationInfo> getAllInstalledApps(Context context) {
        PackageManager packageManager = context.getPackageManager();
        return packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
    }
    /**
     * 获取设备上所有应用的入口 Activity 信息
     * @param context 上下文
     * @return 入口 Activity 列表
     */
    public static List<EntryActivity> getAllInstalledAppEntries(Context context) {
        List<EntryActivity> entryActivities = new ArrayList<>();
        try {
            PackageManager packageManager = context.getPackageManager();
            Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

            // 查询匹配的 Activity
            List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(mainIntent, 0);
            for (ResolveInfo resolveInfo : resolveInfos) {
                String activityName = resolveInfo.activityInfo.name;
                String packageName = resolveInfo.activityInfo.packageName;
                Drawable activityIcon = resolveInfo.loadIcon(packageManager);
                String displayName = resolveInfo.loadLabel(packageManager).toString();
                if (!packageName.equals("com.kld.simplelauncher")) {
                    entryActivities.add(new EntryActivity(packageName, activityName, displayName, activityIcon));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        getLauncherApps(context);
        return entryActivities;
    }

    // 获取所有显示在 Launcher 上的应用 和getAllInstalledAppEntries一样
    public static void getLauncherApps(Context context) {
        PackageManager packageManager = context.getPackageManager();

        // 构造 Intent，查询所有主界面的应用
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);  // 只获取 Launcher 显示的应用

        // 查询所有符合的应用
        List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(mainIntent, 0);

        for (ResolveInfo resolveInfo : resolveInfos) {
            String packageName = resolveInfo.activityInfo.packageName;  // 应用包名
            String activityName = resolveInfo.activityInfo.name;  // 主 Activity 名
            Log.d("LauncherApp", "Package: " + packageName + ", Activity: " + activityName);
        }
    }
}
